import { defineStore } from "pinia";
import { useAllFiles } from "@/store/allFiles";
import { components } from "@/router";
import { RouteLocationNormalizedLoadedGeneric, Router, RouteRecordRaw, useRoute, useRouter } from "vue-router";

function regroupMenuList(data: RouteRecordRaw[], basePath: string = "") {
  // 先过滤出 isNotMenu 不为 true 的项目
  data = data.filter((item) => !item.meta?.isNotMenu);
  return data.map((item: any) => {
    if (item.children && item.children.length > 0) {
      item.children = regroupMenuList(item.children, item.path);
    }
    let data = { ...item, ...item.meta };
    if (item.path[0] === "/") {
      data.path = basePath ? `/${basePath}${item.path}` : `${item.path}`;
    } else {
      data.path = basePath ? `/${basePath}/${item.path}` : `/${item.path}`;
    }
    delete data.component;
    delete data.meta;
    return data;
  });
}

interface HandleFn {
  component: Function;
  javascripts: Function;
  markdowns: Function;
  default: Function;
}

export const useMenu = defineStore("menu", {
  state: (): {
    [key: string]: any;
  } => {
    // 数据
    return {
      defaultActive: "/html",
      isRouter: true,
      menuList: regroupMenuList(components, "component"),
      activeKey: "/html",
      jsMenu: [],
      mdMenu: [],
      activeName: "component",
      router: useRouter(), // 获取路由实例
      route: useRoute(), // 获取路由实例
    };
  },
  actions: {
    // 初始化
    initData() {
      const fileStore = useAllFiles();
      let jsres = fileStore.getFilesByType("javascript");
      this.jsMenu = [];
      for (let i of jsres) {
        this.jsMenu.push({
          path: i.path,
          name: i.path,
          component: "",
          meta: {
            title: i.name,
            icon: "",
            img: "",
            groupName: "",
          },
        });
      }

      let mdres = fileStore.getFilesByType("markdown");
      this.mdMenu = [];
      for (let i of mdres) {
        this.mdMenu.push({
          path: i.path,
          name: i.path,
          component: "",
          meta: {
            title: i.name,
            icon: "",
            img: "",
            groupName: "",
          },
        });
      }
      let pathList = ["component", "javascripts", "markdowns"];
      let activeRouteModule = pathList.find((item) => this.route.path.includes(item)) || "component";
      this.activeName = activeRouteModule;
      this.handleChange(activeRouteModule as "component" | "javascripts" | "markdowns", false);
    },

    handleChange(e: "component" | "javascripts" | "markdowns", toPath: boolean = true) {
      let activeKey = this.route.query.activeKey as string;
      let handleFn: HandleFn = {
        component: () => {
          this.setRouter(true);
          this.regroupMenuList(components, "component");
          toPath && this.setDefaultActive("/component/html");
          toPath && this.router.push("/component/html");
        },
        javascripts: () => {
          let path = toPath ? this.jsMenu[0].path : activeKey || this.jsMenu[0].path;
          this.setRouter(false);
          this.regroupMenuList(this.jsMenu);
          this.setActiveKey(path);
          this.setDefaultActive(path);
          toPath && this.router.push({ path: "/javascripts/js/details", query: { activeKey: path } });
        },
        markdowns: () => {
          let path = toPath ? this.mdMenu[0].path : activeKey || this.mdMenu[0].path;
          this.setRouter(false);
          this.regroupMenuList(this.mdMenu);
          this.setActiveKey(path);
          this.setDefaultActive(path);
          toPath && this.router.push({ path: "/markdowns/markdown/details", query: { activeKey: path } });
        },
        default: () => {
          this.setRouter(true);
          this.regroupMenuList(components, "component");
          toPath && this.setDefaultActive("/component/html");
          toPath && this.router.push("/component/html");
        },
      };
      let fn = handleFn[e] || handleFn.default;
      fn();
    },
    // 设置激活
    setActiveKey(path: string) {
      this.activeKey = path;
    },
    // 设置默认路由
    setDefaultActive(path: string) {
      this.defaultActive = path;
    },
    // 设置路由状态
    setRouter(state: boolean) {
      this.isRouter = state;
    },
    // 重组菜单数据
    regroupMenuList(data: RouteRecordRaw[], basePath: string = "") {
      this.menuList = regroupMenuList(data, basePath);
    },
    // 菜单激活回调
    handleSelect(key: string, route: RouteLocationNormalizedLoadedGeneric, router: Router) {
      this.activeKey = key;
      if (!this.isRouter) {
        router.push({ path: route.path, query: { activeKey: key } });
      }
    },
    // 菜单展开回调
    handleOpen(key: string) {
      console.log("key :>> ", key);
    },
    // 菜单关闭回调
    handleClose(key: string) {
      console.log("key :>> ", key);
    },
  },
});
